<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-03-22
// +—————————————————————————————————————————————————————————————————————

/* 
    腾讯云直播回调
 */

namespace app\appapi\controller;

use cmf\controller\HomeBaseController;
use think\Db;


class LivebackController extends HomeBaseController
{
    public function index(){
        $data = $this->request->param();
        $this->callbacklog('data:'.json_encode($data));
        $rs = array( 'code' => 0 );
        
        if(!$data){
			$this->callbacklog("request para json format error");
			$rs['code']=4001;
			echo json_encode($rs);	
			exit;
		}
		
		if(array_key_exists("t",$data)
				&& array_key_exists("sign",$data)
				&& array_key_exists("event_type",$data) 
				&& array_key_exists("stream_id",$data))
		{
			$check_t = $data['t'];
			$check_sign = $data['sign'];
			$event_type = $data['event_type'];
			$stream_id = $data['stream_id'];
		}else {
			$this->callbacklog("request para error");
			$rs['code']=4002;
			echo json_encode($rs);	
			exit;
		}
		$md5_sign = $this-> GetCallBackSign($check_t);
		if( !($check_sign == $md5_sign) ){
			$this->callbacklog("check_sign error:" . $check_sign . ":" . $md5_sign);
			$rs['code']=4003;
			echo json_encode($rs);
			exit;
		}        
		
		if($event_type == 100){
			/* 回放回调 */
			if(array_key_exists("video_id",$data) && 
					array_key_exists("video_url",$data) &&
					array_key_exists("start_time",$data) &&
					array_key_exists("end_time",$data) ){
						
				$video_id = $data['video_id'];
				$video_url = $data['video_url'];
				$start_time = $data['start_time'];
				$end_time = $data['end_time'];
			}else{
				$this->callbacklog("request para error:回放信息参数缺少" );
				$rs['code']=4002;
				echo json_encode($rs);	
				exit;
			}
		}     
		$ret=0;
		if($event_type == 0){        	
			/* 断流 */
			$ret=$this->stopConversa($stream_id);
		}elseif ($event_type == 1){
            /* 推流 */

		}elseif ($event_type == 8){
            /* 混流 */

		}elseif ($event_type == 200){
            /* 直播截图生成 */

		}elseif ($event_type == 100){
            /* 录制生成 */
			//$duration = $end_time - $start_time;
			//if ( $duration > 60 ){
				$data=array(
					"video_url"=>$video_url,
					//"duration"=>$duration,
					//"file_id"=>$video_id,
				);
		}
        $this->callbacklog($ret );
		$rs['code']=0;
		echo json_encode($rs);
		exit;

    }
    protected function GetCallBackSign($txTime){
		$configpri=getConfigPri();
		$md5_val = md5($configpri['tx_api_key'] . strval($txTime));
		return $md5_val;
	}
	protected function callbacklog($msg){
		file_put_contents(CMF_ROOT .'log/Liveback_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 '.$msg."\r\n",FILE_APPEND);
	}
    protected function stopConversa($stream){
        if($stream==''){
            return 4004;
        }
        $stream_a=explode('_',$stream);
        $uid=$stream_a[0];
        $showid=$stream_a[1];
        
        if(!$uid || !$showid){
            return 4005;
        }
        $this->callbacklog('stream:'.json_encode($stream));
        $this->callbacklog('uid:'.json_encode($uid));
        $this->callbacklog('showid:'.json_encode($showid));
        $info=Db::name('conversa_log')
                ->where(" ( uid={$uid} or liveuid={$uid} ) and showid='{$showid}'")
                ->find();
        $this->callbacklog('info:'.json_encode($info));
		
		 
		
        if(!$info){
            return 4006;
        }
        if($info['status'] ==2){
            return 4007;
        }
        
        $nowtime=time();

        $data=[
            'status'=>2,
            'endtime'=>$nowtime,
        ];
        $length=$nowtime - $info['starttime'];
        $sendtype='0'; //用户给主播发
        if($uid==$info['liveuid']){
            $sendtype='1'; //主播给用户发
            if($length < 10){
                $votes=$info['total'];
                reduceVotes($info['liveuid'],$votes,$votes);
                
                Db::name('user_coinrecord')
                    ->where("action in (2,3) and touid = {$info['liveuid']} and showid={$showid}")
                    ->update(['isdeduct'=>1]);

                $data['total']='0';
            }
        }
        
        Db::name('conversa_log')->where("id={$info['id']}")->update($data);
        
        Db::name('user')->where("id={$info['uid']}")->update( ['online'=>3] );
        Db::name('user')->where("id={$info['liveuid']}")->update( ['online'=>3] );
        
 
        $content='通话时长 '.getLength($length,2);
	
        
 
        /* IM */
        /* 用户给主播发 */
        $ext=[
            'method'=>'call',
            'action'=>'9',
            'type'=>$info['type'],
            'content'=>$content,
        ];
        
        #构造高级接口所需参数
        $msg_content = array();
        //创建array 所需元素
        $msg_content_elem = array(
            'MsgType' => 'TIMCustomElem',       //自定义类型
            'MsgContent' => array(
                'Data' => json_encode($ext),
                'Desc' => '',
            )
        );
        //将创建的元素$msg_content_elem, 加入array $msg_content
        array_push($msg_content, $msg_content_elem);
        
        $account_id=(string)$info['uid'];
        $receiver=(string)$info['liveuid'];
        $api=getTxRestApi();
        $type= $sendtype==0 ? 1 : 2;
        $ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
		
		

        
        /* 主播给用户发 */
        $ext=[
            'method'=>'call',
            'action'=>'8',
            'type'=>$info['type'],
            'content'=>$content,
        ];
        
        #构造高级接口所需参数
        $msg_content = array();
        //创建array 所需元素
        $msg_content_elem = array(
            'MsgType' => 'TIMCustomElem',       //自定义类型
            'MsgContent' => array(
                'Data' => json_encode($ext),
                'Desc' => '',
            )
        );
        //将创建的元素$msg_content_elem, 加入array $msg_content
        array_push($msg_content, $msg_content_elem);
        
        $account_id=(string)$info['liveuid'];
        $receiver=(string)$info['uid'];
        $api=getTxRestApi();
        $type= $sendtype==1 ? 1 : 2;
        $ret = $api->openim_send_msg_custom($account_id, $receiver, $msg_content,$type);
        
        return 0;
    }
}
